<template>
  <div>
    <el-drawer
      v-if="info.type === 'drawer'"
      class="flex-el-drawer track-drawer"
      :size="info.imageUrl ? '70%' : '60%'"
      direction="rtl"
      :wrapperClosable="false"
      :with-header="false"
      :visible.sync="visible"
    >
      <div class="el-drawer__header">
        <span>{{this.title}}</span>
        <button class="el-drawer__close-btn" @click="handleCloseDrawer">
          <el-icon class="el-icon-close"></el-icon>
        </button>
      </div>
      <div class="el-drawer-content">
        <div class="track-info">
          <div class="img-content" v-if="info.imageUrl">
            <pic-upload-module :picInfo="picInfo" :action="[]"></pic-upload-module>
          </div>
          <el-form
            ref="form"
            :model="form"
            :rules="formRules"
            label-position="top"
            label-width="110px"
            size="mini"
          >
            <el-row :gutter="10">
              <el-col :span="12">
                <el-form-item label="埋点名称" prop="trackName">
                  <el-input v-model="form.trackName"></el-input>
                </el-form-item>
              </el-col>
              <el-col :span="12">
                <el-form-item prop="trackId">
                  <span slot="label">
                    埋点标识
                    <el-tooltip content="标识规则：只能以字母开头，内容只能是字母，数字,下划线，长度在6~255位之间" placement="top">
                      <i class="el-icon-question"></i>
                    </el-tooltip>
                  </span>
                  <el-input v-model="form.trackId" :disabled="trackDbId ? true : false"></el-input>
                </el-form-item>
              </el-col>
              <el-col :span="12">
                <el-form-item label="事件名称" prop="eventId">
                  <el-select
                    v-model="form.eventId"
                    placeholder="请选择"
                    :disabled="trackDbId ? true : false"
                    @change="handleEventTypeChange"
                  >
                    <el-option
                      v-for="item in eventTypeList"
                      :key="item.eventId"
                      :label="item.eventName"
                      :value="item.eventId"
                    ></el-option>
                  </el-select>
                </el-form-item>
              </el-col>
              <!-- <el-col :span="12">
                <el-form-item label="动作类型" prop="actionType">
                  <el-select v-model="form.extMessage.actionType" placeholder="请选择">
                    <el-option
                      v-for="item in actionTypeList"
                      :key="item.code"
                      :label="item.value"
                      :value="item.code"
                    ></el-option>
                  </el-select>
                </el-form-item>
              </el-col>
              <el-col :span="12">
                <el-form-item label="动作效果" prop="actionEffect">
                  <el-select v-model="form.extMessage.actionEffect" placeholder="请选择">
                    <el-option
                      v-for="item in actionEffectList"
                      :key="item.code"
                      :label="item.value"
                      :value="item.code"
                    ></el-option>
                  </el-select>
                </el-form-item>
              </el-col>-->
              <el-col :span="24">
                <el-form-item label="埋点时机" prop="extMessage.trackOpportunity">
                  <el-input type="textarea" v-model="form.extMessage.trackOpportunity"></el-input>
                </el-form-item>
              </el-col>
            </el-row>
          </el-form>
        </div>
        <div class="select-property-content">
          <div class="title">已选属性</div>
          <el-table size="mini" border :data="selectPropertiesData" style="width: 100%">
            <!-- <el-table-column
              v-for="item in handleAttributeColumns()"
              :show-overflow-tooltip="true"
              :sortable="item.sortable"
              :min-width="item.width"
              :key="item.prop"
              :prop="item.prop"
              :label="item.label"
            >
              <template slot-scope="scope">{{scope.row[item.prop] || "--"}}</template>
            </el-table-column>
            <el-table-column prop="notes" label="注释" min-width="200">
              <template slot-scope="scope">
                <el-input
                  size="mini"
                  placeholder="根据实际配置设置"
                  v-model="selectPropertiesRemarks['explain' + scope.row.id]"
                  @input="(value) => handleChangeRemark(value, scope)"
                ></el-input>
              </template>
            </el-table-column>-->
            <el-table-column prop="propertyName" width="160" label="显示名"></el-table-column>
            <el-table-column prop="propertyValue" label="属性值">
              <template slot-scope="scope">
                <el-input size="mini" placeholder="根据实际配置设置" v-model="scope.row.propertyValue"></el-input>
              </template>
            </el-table-column>
            <el-table-column prop="remark" label="说明"></el-table-column>
            <el-table-column prop="action" width="80" label="操作">
              <template slot-scope="scope">
                <el-button size="mini" type="text" @click="handleDeleteProperty(scope)">移除</el-button>
              </template>
            </el-table-column>
          </el-table>
        </div>
        <div class="all-property-content">
          <div class="title">全部属性</div>
          <div class="search">
            <el-select size="mini" v-model="search.category">
              <el-option
                v-for="item in categoryList"
                :key="item.code"
                :label="item.value"
                :value="item.code"
              ></el-option>
            </el-select>
            <el-input size="mini" v-model="search.propertyId" placeholder="输入属性名称"></el-input>
            <el-input size="mini" v-model="search.propertyName" placeholder="输入显示名称"></el-input>
            <el-button size="mini" type="primary" @click="handleSearchProperty">查询</el-button>
          </div>
          <el-table size="mini" border :data="allPropertiesData" style="width: 100%">
            <!-- <el-table-column
              v-for="item in allPropertyColumns"
              :show-overflow-tooltip="true"
              :sortable="item.sortable"
              :min-width="item.width"
              :key="item.prop"
              :prop="item.prop"
              :label="item.label"
            >
              <template slot-scope="scope">{{scope.row[item.prop] || "--"}}</template>
            </el-table-column>-->
            <el-table-column prop="propertyName" width="160" label="显示名"></el-table-column>
            <el-table-column prop="remark" label="说明"></el-table-column>
            <el-table-column prop="action" label="操作" width="80">
              <template slot-scope="scope">
                <el-button size="mini" type="text" @click="handleSelectAttr(scope)">选择</el-button>
              </template>
            </el-table-column>
          </el-table>
          <el-pagination
            @size-change="handleDrawerSize"
            @current-change="handleDrawerCurrent"
            :current-page="search.currentPage"
            :page-sizes="[10, 20, 30, 40]"
            :page-size="search.pageSize"
            background
            layout="total, prev, pager, next, sizes"
            :total="propertyTotal"
          ></el-pagination>
        </div>
      </div>
      <div class="el-drawer-footer">
        <el-button size="mini" type="text" @click="handleCloseDrawer">取消</el-button>
        <el-button size="mini" type="primary" @click="handleSaveDrawer">保存</el-button>
      </div>
    </el-drawer>
    <el-dialog
      v-else
      :title="title"
      :visible.sync="visible"
      width="60%"
      :before-close="handleCloseDialog"
    >
      <div class="select-property-content">
        <div class="title">已选属性</div>
        <el-table size="mini" border :data="selectPropertiesData" style="width: 100%">
          <!-- <el-table-column
            v-for="item in handleAttributeColumns()"
            :show-overflow-tooltip="true"
            :sortable="item.sortable"
            :min-width="item.width"
            :key="item.prop"
            :prop="item.prop"
            :label="item.label"
          >
            <template slot-scope="scope" v-if="item.prop === 'propertyValue'">
              <el-input
                size="mini"
                placeholder="请输入属性值"
                v-if="info.isAction"
                v-model="selectPropertiesRemarks['explain' + scope.row.id]"
                @input="(value) => handleChangeRemark(value, scope)"
              ></el-input>
              <span v-else>{{scope.row["propertyValue"] || "--"}}</span>
            </template>
            <template slot-scope="scope" v-else>{{scope.row[item.prop] || "--"}}</template>
          </el-table-column>
          <el-table-column prop="explain" label="注释" min-width="200">
            <template slot-scope="scope">
              <el-input
                size="mini"
                placeholder="根据实际配置设置"
                v-if="info.isAction"
                v-model="selectPropertiesRemarks['explain' + scope.row.id]"
                @input="(value) => handleChangeRemark(value, scope)"
              ></el-input>
              <span v-else>{{scope.row["explain"] || "--"}}</span>
            </template>
          </el-table-column>-->
          <el-table-column prop="propertyName" width="160" label="显示名"></el-table-column>
          <el-table-column prop="propertyValue" label="属性值"></el-table-column>
          <el-table-column prop="remark" label="说明"></el-table-column>
          <el-table-column prop="action" width="80" label="操作" v-if="info.isAction">
            <template slot-scope="scope">
              <el-button size="mini" type="text" @click="handleDeleteProperty(scope)">移除</el-button>
            </template>
          </el-table-column>
        </el-table>
      </div>
      <div class="all-property-content">
        <div class="title">全部属性</div>
        <div class="search">
          <el-select size="mini" v-model="search.category" placeholder="请选择类别">
            <el-option
              v-for="item in categoryList"
              :key="item.code"
              :label="item.value"
              :value="item.code"
            ></el-option>
          </el-select>
          <el-input size="mini" v-model="search.propertyId" placeholder="输入属性名称"></el-input>
          <el-input size="mini" v-model="search.propertyName" placeholder="输入显示名称"></el-input>
          <el-button size="mini" type="primary" @click="handleSearchProperty">查询</el-button>
        </div>
        <el-table
          size="mini"
          border
          :data="allPropertiesData"
          style="width: 100%"
          v-loading="tableLoading"
        >
          <!-- <el-table-column
            v-for="item in allPropertyColumns"
            :show-overflow-tooltip="true"
            :sortable="item.sortable"
            :min-width="item.width"
            :key="item.prop"
            :prop="item.prop"
            :label="item.label"
          >
            <template slot-scope="scope">{{scope.row[item.prop] || "--"}}</template>
          </el-table-column>-->
          <el-table-column prop="propertyName" width="160" label="显示名"></el-table-column>
          <el-table-column prop="remark" label="说明"></el-table-column>
          <el-table-column prop="action" label="操作" width="80" v-if="info.isAction">
            <template slot-scope="scope">
              <el-button size="mini" type="text" @click="handleSelectAttr(scope)">选择</el-button>
            </template>
          </el-table-column>
        </el-table>
        <el-pagination
          @size-change="handleSize"
          @current-change="handleCurrent"
          :current-page="search.currentPage"
          :page-sizes="[10, 20, 30, 40]"
          :page-size="search.pageSize"
          background
          layout="total, prev, pager, next, sizes"
          :total="propertyTotal"
        ></el-pagination>
      </div>
      <span slot="footer" class="dialog-footer">
        <el-button size="mini" @click="handleCloseDialog">取 消</el-button>
        <el-button size="mini" type="primary" @click="handleSaveDialog">确 定</el-button>
      </span>
    </el-dialog>
  </div>
</template>

<script>
export default {
  name: "formModule",
  data() {
    return {
      requirementId: null,
      pageId: null,
      trackDbId: null,
      title: "添加埋点",
      visible: false,
      // pic-upload
      picInfo: {
        url: "",
        iconPosition: []
      },
      // joker
      form: {
        trackName:null, // 埋点名称
        trackId:null,   // 埋点标识
        eventId:null,   // 事件名称
        extMessage: {
          trackOpportunity:'', // 埋点时机
          actionType:null,     // 动作类型
          actionEffect:null,    // 动作效果
        }
      },
      formRules: {
        trackName: [
          { required: true, message: "请填写埋点名称", trigger: "blur" }
        ],
        trackId: [
          { required: true, message: "请填写埋点标识", trigger: "blur" }
        ],
        eventId: [
          { required: true, message: "请选择事件类型", trigger: "change" }
        ],
        extMessage: {
          trackOpportunity: [
            { required: true, message: "请填写埋点时机", trigger: "blur" }
          ]
        }
      },
      categoryList: [],
      dataTypeList: [],
      propertyTypeList: [],
      actionEffectList: [], // 动作效果数组
      actionTypeList: [], // 动作类型数组
      search: {
        productCode: null, // 产品编码
        // 查询属性条件
        currentPage: 1,
        pageSize: 10,
        propertyId: null, // 事件属性名称
        propertyName: "", // 事件显示名称
        category: null // 类别
      },
      propertyTotal: 0,
      selectPropertiesData: [], // 已选属性数组
      selectPropertiesId: [], // 已选属性id数组
      selectPropertiesRemarks: {}, // 用于已选属性注释响应式交互
      tableLoading: false,
      allPropertyColumns: [
        {
          prop: "categoryValue",
          label: "类别",
          width: 80
        },
        {
          prop: "propertyId",
          label: "属性名",
          width: 100
        },
        {
          prop: "propertyName",
          label: "显示名",
          width: 100
        },
        {
          prop: "propertyTypeValue",
          label: "属性类型",
          width: 80
        },
        {
          prop: "dataTypeValue",
          label: "数据类型",
          width: 80
        },
        {
          prop: "verifyRule",
          label: "验证规则",
          width: 120
        },
        {
          prop: "remark",
          label: "说明",
          width: 120
        }
      ],
      allPropertiesData: []
    };
  },
  props: {
    info: Object
  },
  watch: {
    info: {
      handler(val) {
        if (val) {
          this.$store.dispatch("getPropertyTypeList");
          this.search.productCode = val.treeMenu.data[0].productCode; // 产品编码
          this.handleQueryPropertyPropertyList(val);
          this.visible = true;
          let { requirementId, pageId, trackDbId, type, imageUrl } = val;
          this.picInfo.url = imageUrl;
          this.requirementId = requirementId;
          this.pageId = pageId;
          this.trackDbId = trackDbId;
          if (type === "drawer") {
            this.$store.dispatch("getEventTypeList");
            this.handleQueryActionList("actionType");
            this.handleQueryActionList("actionEffect");
            // if (trackDbId) {
            //   // this.handleQueryEvent();
            // } else {
            //   this.form = { 
            //     extMessage: {}
            //   };
            // }
            this.title = trackDbId || trackDbId === 0 ? "编辑埋点" : "添加埋点";
          } else if (type === "dialog") {
            this.title = "公共属性";
            this.handleInitSelectedProperties(val.publicProperties.concat([]));
          }
        }
      },
      deep: true
    }
  },
  computed: {
    eventTypeList() {
      return this.$store.state.publicData.eventTypeList;
    }
  },
  created() {},
  mounted() {},
  methods: {
    formClear(){
      this.form = {
        trackName:null, // 埋点名称
        trackId:null,   // 埋点标识
        eventId:null,   // 事件名称
        extMessage: {
          trackOpportunity:'', // 埋点时机
          actionType:null,     // 动作类型
          actionEffect:null,    // 动作效果
        }
      }
    },
    // 查询事件属性类型列表
    async handleQueryPropertyPropertyList(val) {
      let arr = ["category", "propertyType", "dataType"];
      const promise = arr.map(i => {
        return this.$applicationApi.property_property({
          type: i
        });
      });
      const res = await Promise.all(promise);
      if (res) {
        this.categoryList = res[0].value.list;
        this.propertyTypeList = res[1].value.list;
        this.dataTypeList = res[2].value.list;
        this.handleQueryPropertiesData();
        if (this.trackDbId) {
          this.handleQueryEvent();
        } else {
          let _arr = JSON.parse(JSON.stringify(val.treeMenu.data));
          this.trackNameTrackId_Init(_arr, val.pageId); // 初始化埋点名称和埋点标识
        }
      }
    },
    // 查询已选属性接口
    async handleQueryPropertiesDataRead() {
      let res = await this.$applicationApi.property_list({
        currentPage: 1,
        productCode: this.search.productCode,
        pageSize: 1000,
        propertyId: null, // 事件属性名称
        propertyName: null, // 事件显示名称
        category: null, // 类别
        eventId: this.form.eventId // 所选事件名称
      });
      if (res) {
        let { list } = res.value;
        list = this.handleFormatProperTiesList(list);
        this.selectPropertiesData = list.splice(0, 4);
      }
    },
    // 查询全部属性接口
    async handleQueryPropertiesData() {
      this.tableLoading = true;
      try {
        let res = await this.$applicationApi.property_list(this.search);
        if (res) {
          let { list, total } = res.value;
          list = this.handleFormatProperTiesList(list);
          this.allPropertiesData = list;
          this.propertyTotal = total;
        }
        this.tableLoading = false;
      } catch (e) {
        this.tableLoading = false;
      }
    },
    // 添加情况下，获取埋点标识和埋点名称初始值函数  joker
    //  arr: 树形导航   id: 当前选中页面标识  name: 返回显示的埋点名称  trackId: 返回显示的埋点标识
    trackNameTrackId_Init(arr, id, name = "", trackId = "") {
      arr.map(_i => {
        if (_i.pageId === id) {
          this.form.trackName = name + _i.pageName + "_";
          this.form.trackId = trackId + _i.pageId + "_";
        } else if (_i.pageId !== id && _i.children) {
          this.trackNameTrackId_Init(
            _i.children,
            id,
            name + _i.pageName + "_",
            trackId + _i.pageId + "_"
          );
        }
      });
    },
    // 查询埋点详情
    async handleQueryEvent() {
      let res = await this.$eventApi.eventQuery({
        id: this.trackDbId
      });
      if (res) {
        this.form = res.value;
        let { extMessage, fieldAttributes } = res.value;
        if (!extMessage || typeof extMessage === "string") {
          this.form.extMessage = {};
        }
        fieldAttributes = this.handleFormatProperTiesList(fieldAttributes);
        this.handleInitSelectedProperties([].concat(fieldAttributes));
      }
    },
    // 选择事件类型
    handleEventTypeChange(val) {
      let eventItem = {};
      console.log(val,22)
      this.eventTypeList.filter(item => {
        if (item.eventId === val) {
          eventItem = item;
          switch (val) {
            case "hitEvent": // 点击事件
              this.form.extMessage.trackOpportunity =
                "用户点击该按钮时/研发人员可根据实际情况确定埋点时机";
              break;
            case "pageEvent": // 曝光事件
              this.form.extMessage.trackOpportunity =
                "对应模块100%露出时/研发人员可根据时机情况确定埋点时机";
              break;
            case "orderEvent": // 订单事件
              this.form.extMessage.trackOpportunity =
                "订单完成或订单页面加载完成时/研发人员可根据实际情况确定埋点时机";
              break;
            case "loginEvent": // 登录事件
              this.form.extMessage.trackOpportunity =
                "用户登录成功时/研发人员可根据实际情况确定埋点时机";
              break;
            case "page_view_event": // 页面浏览事件
              this.form.extMessage.trackOpportunity =
                "页面加载完成时/研发人员可根据实际情况确定埋点时机";
              break;
            default:
              this.form.extMessage.trackOpportunity = "";
          }
        }
      });
      this.form.extMessage.actionType = eventItem.actionType;
      this.form.extMessage.actionEffect = eventItem.actionEffect;
      this.handleQueryPropertiesDataRead(); // 事件名称更改后，刷新已选属性
    },
    // 已选属性columns
    handleAttributeColumns() {
      let columns = [].concat(this.allPropertyColumns);
      let obj = {
        prop: "propertyValue",
        label: "属性值",
        width: 100
      };
      columns.splice(3, 2, obj);
      return columns;
    },
    // 点击查询属性
    handleSearchProperty() {
      this.handleQueryPropertiesData();
    },
    handleFormatProperTiesList(list) {
      list.forEach((item, index) => {
        this.categoryList.forEach(category => {
          if (category.code === item.category) {
            list[index].categoryValue = category.value;
          }
        });
        this.dataTypeList.forEach(dataType => {
          if (dataType.code === item.dataType) {
            list[index].dataTypeValue = dataType.value;
          }
        });
        this.propertyTypeList.forEach(propertyType => {
          if (propertyType.code === item.propertyType) {
            list[index].propertyTypeValue = propertyType.value;
          }
        });
      });
      return list;
    },
    handleSize(size) {
      this.search.currentPage = 1;
      this.search.pageSize = size;
      this.handleQueryPropertiesData();
    },
    handleCurrent(page) {
      this.search.currentPage = page;
      this.handleQueryPropertiesData();
    },
    handleDrawerSize(size) {
      this.search.currentPage = 1;
      this.search.pageSize = size;
      this.handleQueryPropertiesData();
    },
    handleDrawerCurrent(page) {
      this.search.currentPage = page;
      this.handleQueryPropertiesData();
    },
    // 默认已选属性 
    handleInitSelectedProperties(data) {
      this.selectPropertiesId = [];
      this.selectPropertiesData = [];
      this.selectPropertiesRemarks = {};
      this.selectPropertiesData = [].concat(data);
      data.forEach(item => {
        this.selectPropertiesId.push(item.id);
        this.$set(
          this.selectPropertiesRemarks,
          "explain" + item.id,
          item.explain
        );
      });
    },
    // 清除已选属性、全部属性查询条件、form表单
    handleClearSelectedProperties() {
      this.selectPropertiesId = [];
      this.selectPropertiesData = [];
      this.selectPropertiesRemarks = {};
      this.formClear();
      this.search = {
        productCode: null,
        currentPage: 1,
        pageSize: 10,
        propertyId: null,
        category: null
      };
    },
    // 选择属性
    handleSelectAttr(scope) {
      let { id, explain } = scope.row;
      let bool  = false;
      this.selectPropertiesData.map(_i => {
        if (_i.id == id) {
          this.$message.info("您已经选了当前属性!");
          bool = true;
        }
      });
      if (this.selectPropertiesId.indexOf(id) === -1 && !bool) {
        this.selectPropertiesId.push(id);
        this.selectPropertiesData.push(scope.row);
        this.$set(this.selectPropertiesRemarks, "explain" + id, explain);
      } else if(this.selectPropertiesId.indexOf(id) !== -1 && !bool) {
        this.$message.info("您已经选了当前属性!");
      }
    },
    // 注释改变
    handleChangeRemark(value, scope) {
      let { row } = scope;
      this.selectPropertiesData.forEach(item => {
        if (row.id === item.id) {
          item.explain = value;
        }
      });
    },
    // 移除属性
    handleDeleteProperty(scope) {
      let { $index } = scope;
      this.selectPropertiesData.splice($index, 1);
      this.selectPropertiesId.splice($index, 1);
    },
    // 保存埋点
    handleSaveDrawer() {
      let message = "";
      this.$refs["form"].validate(async valid => {
        if (valid) {
          let { trackId, trackName, eventId, extMessage } = this.form;
          let data = {
            trackId,
            trackName,
            eventId,
            requirementId: this.requirementId,
            pageId: this.pageId,
            extMessage: {
              actionType: extMessage.actionType,
              actionEffect: extMessage.actionEffect,
              trackOpportunity: extMessage.trackOpportunity
            },
            fieldAttributes: this.selectPropertiesData
          };
          let res;
          if (this.trackDbId) {
            message = "编辑";
            data.id = this.trackDbId;
            res = await this.$eventApi.eventUpdate(data);
          } else {
            message = "添加";
            res = await this.$eventApi.eventAdd(data);
          }

          if (res.success) {
            this.handleClearSelectedProperties();
            this.$refs.form.resetFields();
            this.visible = false;
            this.$message({
              showClose: true,
              message: message + "成功",
              type: "success"
            });
            this.$emit("saveEvent", true);
          }
        }
      });
    },
    // 关闭drawer
    handleCloseDrawer() {
      this.handleClearSelectedProperties();
      this.$refs.form.resetFields();
      this.visible = false;
    },
    // 关闭dialog
    handleCloseDialog() {
      this.handleClearSelectedProperties();
      this.visible = false;
    },
    // 保存
    handleSaveDialog() {
      this.$emit("saveProperties", this.selectPropertiesData);
      this.handleClearSelectedProperties();
      this.visible = false;
    },
    // 查询动作类型、动作效果
    async handleQueryActionList(type) {
      let res = await this.$applicationApi.event_prefabricated({
        type
      });
      if (res) {
        let { list } = res.value;
        if (type === "actionType") {
          this.actionTypeList = list;
        }
        if (type === "actionEffect") {
          this.actionEffectList = list;
        }
      }
    }
  }
};
</script>

<style scoped lang="scss">
.track-drawer .el-drawer-content,
.el-dialog__body {
  .track-info {
    display: flex;
    .img-content {
      width: 45%;
      padding: 10px 20px;
    }
  }

  .select-property-content,
  .all-property-content {
    .title {
      padding: 10px;
      position: relative;
      &:before {
        content: "";
        display: block;
        position: absolute;
        left: 0;
        top: 50%;
        -webkit-transform: translateY(-50%);
        -moz-transform: translateY(-50%);
        -ms-transform: translateY(-50%);
        -o-transform: translateY(-50%);
        transform: translateY(-50%);
        width: 3px;
        height: 15px;
        background-color: #01b27a;
      }
    }
  }

  .all-property-content {
    .search {
      margin-bottom: 10px;

      & > .el-input {
        width: 172px;
        margin-left: 10px;
      }

      & > .el-button {
        margin-left: 10px;
      }
    }
  }
}
</style>
